<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <div>
        <input id="name" placeholder="请输入名称">
        <button onclick="createSocket()">加入聊天室</button>
        <button onclick="closeChat()">退出</button>
    </div>
    <div>
        <textarea id="msg" placeholder="请输入聊天内容"></textarea>
        <button onclick="sendMsg()">发送消息</button>

    </div>
    <div id="dvmsgs">
        <div>
            聊天消息内容区域
        </div>
        <div style="clear: both;float: left;margin-left: 20px">
            别人说
        </div>
        <div style="clear: both;float: right;margin-right: 20px">
            自己说
        </div>
    </div>
</div>
<script>
    let ws = null;
    let timer = null;
    function createSocket() {
        console.log("连接服务器")
        let socketUrl = `ws://127.0.0.1:8080/server/`+document.getElementById("name").value;
        ws = new WebSocket(socketUrl);
        ws.addEventListener("open",this.openHandle);
        ws.addEventListener("close",this.closeHandle);
        ws.addEventListener("message",this.messageHandle);
        ws.addEventListener("error",this.errorHandle);

    }

    function openHandle() {
        console.log("socket连接成功")
    }

    function closeChat(){
        ws.close()
    }
    function sendMsg(){
        let msg=document.getElementById("msg").value
        ws.send(msg)
        let d=document.getElementById("dvmsgs");
        d.innerHTML=d.innerHTML+"<div style=\"clear: both;float: right;margin-right: 20px\">"+"我说："+msg+ "</div>";
        document.getElementById("msg").value=""
    }
    function closeHandle() {
        console.log("socket已关闭")
        // 断开重连
        restartWs();
    }
    function messageHandle(e) {
        console.log("socket接收消息")
        console.log(e)
        let d=document.getElementById("dvmsgs");
        d.innerHTML=d.innerHTML+"<div style=\"clear: both;float: left;margin-left: 20px\">\n" +
            e.data +
            "</div>";
    }
    function errorHandle() {
        console.log("socket错误!!!")
    }
    // 断开重连
   function restartWs() {
        console.log("socket连接失败,准备重连...")
        timer = setInterval(() => {
            this.createSocket();
            if (ws && ws.readyState === 0) {
                clearInterval(timer);
                timer = null;
            }
        },2000)
    }
</script>
</body>
</html>